(function(window){
	const Promise = function(executor){
		this.state = "pending";
		this.result = undefined;
		const _resolved = function(value){
			if(this.state !== "pending") return;
			// 将状态更改为成功
			this.state = "fulfilled";
			// 接收的值为成功值
			this.result = value
		}
		const _rejected = function(value){
			if(this.state !== "pending") return;
			// 将状态更改为失败
			this.state = "rejected";
			// 将失败值设置为value的值
			this.result = value;
		}
		try{
			// 执行器函数是同步调用的
			executor(_resolved.bind(this),_rejected.bind(this));
		}catch (err){
			_rejected.call(this,err);
		}
		
		console.log("over");
		
	}
	Object.assign(Promise.prototype,{
		// onResolved:成功回调函数
		// onRejected:失败回调函数
		then(onResolved,onRejected){
			return new Promise((resolve,reject)=>{
				setTimeout(()=>{
					// 如果状态为失败调用失败回调，成功调用成功回调
					if(this.state === "fulfilled")
						try{
							// value:成功回调的返回值
							const value = onResolved(this.result);
							// 判断是不是为Promise实例
							if(value instanceof Promise){
							     value.then((v)=>{
									 // value是成功，值为v
								     resolve(v);
							     },(s)=>{
									 reject(s);
							     })
							}else{
								resolve(value);
							}
						}catch(err){
							// 产生异常
							reject(err);
						}
						
					else if(this.state === "rejected"){
						try{
							// value:成功回调的返回值
							const value = onRejected(this.result);
							// 判断是不是为Promise实例
							if(value instanceof Promise){
								value.then((v)=>{
									// value是成功，值为v
									resolve(v);
								},(s)=>{
									reject(s);
								})
							}else{
								resolve(value);
							}
						}catch(err){
							// 产生异常
							reject(err);
						}
					}
				})
			})
			
			
		}
	})
	window.Promise = Promise;
})(window);
